<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="图书名称">
            <a-input v-decorator="['search']" placeholder="请输入图书名称" />
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button
              type="primary"
              icon="edit"
              @click="handleNameAuth()"
              :disabled="!queryParam.search || loadData.length === 0"
              >修改搜索授权</a-button
            >
          </a-form-item>
        </a-form>
      </a-row>

      <!-- 操作板块 -->
      <div class="row-item-tab clearfix row-item-flex">
        <a-button class="fl-l" type="primary" icon="edit" @click="handleAuth()" :disabled="!hasSelected"
          >修改选中授权</a-button
        >
        <a-button class="fl-l" type="primary" icon="plus" @click="handleEdit(null)">创建书籍</a-button>
        <div class="row-item-switch">
          <span>是否开启授权:</span>
          <a-switch
            checked-children="是"
            un-checked-children="否"
            default-checked
            :checked="checked"
            @click="handleSwitch"
          />
        </div>
      </div>
    </div>
    <s-table
      ref="table"
      rowKey="id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="status" slot-scope="text, item">
        <a-tag class="cur-p" :color="text === 10 ? 'green' : 'red'" @click="handleUpdateStatus(item.id, text)">{{
          text === 10 ? '正常' : '停用'
        }}</a-tag>
      </span>
      <span slot="auth" slot-scope="text, item">
        <!-- <span style="color: red" v-if="text">需要授权</span>
        <span v-else>-</span> -->
        <a-switch
          checked-children="开启"
          un-checked-children="关闭"
          default-checked
          :checked="!!text"
          @click="changeBookAuth(item)"
        />
      </span>
      <!-- 操作 -->
      <span class="actions" slot="action" slot-scope="text, item">
        <a v-action:edit @click="handleEdit(item)">编辑</a>
        <router-link :to="{ path: '/book/page', query: { bookId: item.id, bookName: item.name } }"
          >页面列表</router-link
        >
        <!-- <router-link
          v-if="item.auth"
          :to="{ path: '/book/inviteBatch', query: { bookId: item.id, bookName: item.name } }"
          >邀请码</router-link
        > -->
        <a style="color: red" v-action:delete @click="handleDelete(item.id)">删除</a>
      </span>
    </s-table>
    <ItemForm ref="Form" @handleSubmit="handleRefresh(false)" />
    <a-modal v-model="visible" title="批量修改选中授权" @ok="handleOk">
      <a-radio-group v-model="value">
        <a-radio :value="1"> 启用 </a-radio>
        <a-radio :value="0"> 禁用 </a-radio>
      </a-radio-group>
    </a-modal>
  </a-card>
</template>

<script>
import * as Api from '@/api/book'
import { STable } from '@/components'
import ItemForm from './modules/ItemForm'

export default {
  name: 'Index',
  components: {
    STable,
    ItemForm
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length
    }
  },
  data() {
    return {
      // 授权配置开关
      checked: false,
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      selectedRowKeys: [],
      visible: false,
      value: '',
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '书籍名称',
          dataIndex: 'name'
        },
        {
          title: '书籍说明',
          dataIndex: 'desc'
        },
        {
          title: '是否授权',
          dataIndex: 'auth',
          scopedSlots: { customRender: 'auth' }
        },
        {
          title: '页面数量',
          dataIndex: 'page_num'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (param) => {
        return Api.list({ ...param, ...this.queryParam }).then((response) => response.data.list)
      }
    }
  },
  created() {
    this.getAuthDetails()
  },
  methods: {
    /**
     * 删除记录
     */
    handleDelete(id) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {
          return Api.del({ id })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },

    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },
    // 修改状态()
    handleUpdateStatus(id, state) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要' + (state === 10 ? '停用' : '启用') + '该记录吗?',
        onOk() {
          return Api.changeStatus({ id })
            .then((result) => {
              // 显示成功
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    handleEdit(item) {
      this.$refs.Form.edit({ ...(item?.adRel || {}), ...item })
    },
    getAuthDetails() {
      Api.authDetail().then((result) => {
        if (result.data.book_auth === 1) {
          this.checked = true
        } else {
          this.checked = false
        }
      })
    },
    handleSwitch() {
      Api.changeAuth().then((result) => {
        this.checked = !this.checked
      })
    },
    changeBookAuth(item) {
      Api.changeBookAuth({ id: item.id }).then((result) => {
        item.auth = item.auth === 0 ? 1 : 0
      })
    },
    onSelectChange(val) {
      this.selectedRowKeys = val
    },
    handleAuth() {
      this.visible = true
    },
    handleOk(e) {
      console.log(e)
      if (parseInt(this.value) >= 0) {
        Api.changeBookAuthList({ ids: this.selectedRowKeys, auth: this.value }).then((result) => {
          this.visible = false
          this.$message.success('修改成功!', 1.5)
          this.selectedRowKeys = []
          this.handleRefresh()
        })
      } else {
        this.$message.error('请选择授权状态!', 1.5)
      }
    },
    handleNameAuth() {
      const app = this
      const modal = this.$confirm({
        title: '您确定要修改搜索名称授权吗?',
        content: this.$createElement({
          data() {
            return {
              radioValue: ''
            }
          },
          methods: {
            handleChange(value) {
              this.radioValue = value
              app.value = value
            }
          },
          render(h) {
            return h('div', [
              h(
                'a-radio-group',
                {
                  props: {
                    value: this.radioValue
                  },
                  on: {
                    input: this.handleChange
                  }
                },
                [
                  h(
                    'a-radio',
                    {
                      props: {
                        value: 1
                      }
                    },
                    '启用'
                  ),
                  h(
                    'a-radio',
                    {
                      props: {
                        value: 0
                      }
                    },
                    '禁用'
                  )
                ]
              )
            ])
          }
        }),
        onOk() {
          if (parseInt(app.value) >= 0) {
            return Api.changeBookAuthByName({ name: app.queryParam.search, auth: app.value })
              .then((result) => {
                // 显示成功
                app.$message.success('修改成功!', 1.5)
                app.handleRefresh()
              })
              .finally((result) => modal.destroy())
          } else {
            this.$message.error('请选择授权状态!', 1.5)
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}
.row-item-flex {
  display: flex;
  align-items: center;
  .row-item-switch {
    margin-left: 20px;
    span {
      margin-right: 16px;
    }
  }
}
</style>
